<?php
namespace app\controller;

use app\BaseController;
use app\command\MqttServer;
use app\model\AlbumFeature;
use app\model\AlbumPhoto;
use app\model\Faces;
use app\model\FacesFeature;
use app\model\Feature;
use app\model\Task;
use app\process\CalFeature;
use fast\Http;
use Illuminate\Support\Facades\Redis;
use think\api\Client;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;
use think\facade\Request;
use Swoole\Server;

class Index extends BaseController
{

    public function iii(){
        //event('swoole.websocket.ApiEvent', 111);
        //$ws=new \think\swoole\Websocket();
        //$ws->
        $data['aa']=111;
        $data['bb']=222;
        Http::post('http://127.0.0.1:9503',['content'=>json_encode($data)]);
        /*$ws = app('think\swoole\Websocket');
        $ws->push('aa');*/

        /*$ser = app('\Swoole\Server');

        foreach ($ser->connections as $fd) {
            $ser->send($fd,1111);
            // 这里就可以执行推送了
        }*/
    }
    public function index()
    {
        return '<style type="text/css">*{ padding: 0; margin: 0; } div{ padding: 4px 48px;} a{color:#2E5CD5;cursor: pointer;text-decoration: none} a:hover{text-decoration:underline; } body{ background: #fff; font-family: "Century Gothic","Microsoft yahei"; color: #333;font-size:18px;} h1{ font-size: 100px; font-weight: normal; margin-bottom: 12px; } p{ line-height: 1.6em; font-size: 42px }</style><div style="padding: 24px 48px;"> <h1>:) </h1><p> ThinkPHP V' . \think\facade\App::version() . '<br/><span style="font-size:30px;">14载初心不改 - 你值得信赖的PHP框架</span></p><span style="font-size:25px;">[ V6.0 版本由 <a href="https://www.yisu.com/" target="yisu">亿速云</a> 独家赞助发布 ]</span></div><script type="text/javascript" src="https://tajs.qq.com/stats?sId=64890268" charset="UTF-8"></script><script type="text/javascript" src="https://e.topthink.com/Public/static/client.js"></script><think id="ee9b1aa918103c4fc"></think>';
    }

    public function hello($name = 'ThinkPHP6')
    {
        return 'hello,' . $name;
    }

    public function test(){
        $msg='{"album_id":"6280ab310dab39000717c519","album_level":2,"album_name":"政府街社区-涉毒布控","album_note":"","album_photo_id":"200-AAABgNIOYtUAxip6AAAAAg==","album_photo_url":"http://10.229.0.19:8080/v5/faces/200-AAABgNIOYtUAxip6AAAAAg==/image/full","birth_date":"","capture_face_url":"http://10.229.0.19:8080/v5/resources/data?uri=weed%3A%2F%2F12484%2C081ad3d45f49bad1&contentType=image/jpeg","capture_panorama_url":"http://10.229.0.19:8080/v5/resources/data?uri=weed%3A%2F%2F8635%2C081ad3d5ea4e5aee&contentType=image/jpeg","capture_time":"2022-05-17 20:49:47.408","capture_video_url":"","device_id":"6358161325884416","device_no":"","gender":2,"identify_list":[{"card_no":"511027197311085463","card_type":1}],"name":"晋秀","nation_desc":"","native":"","photo_id":"6283992fc897ae0008011910","rect":{"height":82,"left":82,"top":85,"width":77},"score":96.64,"warning_id":"01G3912FWGPVKEG1VCGHVQ4JPRfe609b039acafbe4ec34084bd9b686f9-0"}';
        try {
            $json_msg=json_decode($msg,true);
            $env=true;
            //$env=false;
            $albums=$this->getAlbum();
            $camares=$this->getCamare();
            $shequs=$this->getShequ();
            Log::info("albums:".json_encode($albums));

            $dldcode='jygd'.md5($json_msg['warning_id']);
            if($env){
                $data['username']='znyjdj';
                $data['password']='znyjdj1234';
                $url='http://171.221.172.148:18081/tgdld/outwardinterfaces/event/eventOutwardController/addEvent.do';
            }else{
                $data['username']='jktest';
                $data['password']='ab12345678';
                $url='http://xzdz.yinhaiyun.com/dldplus/outwardinterfaces/event/eventOutwardController/addEvent.do';
            }
            $device=$camares[$json_msg['device_id']];
            $shid=$device['sqid'];
            $shequ=$shequs[$shid];
            $note=$albums[$json_msg['album_id']];
            $notes=explode("-",$note);
            $album_name=explode('-',$json_msg['album_name']);
            $insert_id=Db::table('send_msg')->insertGetId(['queue_msg'=>$msg,'create_time'=>date('Y-m-d H:i:s'),'send_id'=>$dldcode]);
            if($notes&&count($notes)>2&&$album_name>1){
                $content_type=[
                    '100013'=>'在册精神病人',
                    '100003'=>'在册涉毒人员',
                    '100019'=>'疑似上访聚集人员',
                    '100033'=>'疑似在逃人员',
                    '100007'=>'疑似涉黄人员'
                ];
                $data['sjddl']=substr($notes[0],0,3);
                $data['eventcategory']=$notes[0];
                $album_name=explode('-',$json_msg['album_name']);
                $data['eventtitle']=$shequ['name'].'-'.$album_name[1];
                $data['dldcode']=$dldcode;//报警ID
                $data['shuqiu_type']='10';
                $data['eventtype']='01';
                //$addresss=explode('-',$json_msg['album_name']);
                $data['eventaddress']='简阳市'.$shequ['name'].$device['position'];
                $data['eventlevel']='00';
                $data['accesslevel']='2';
                $data['eventcontent']=$album_name[0].$content_type[$notes[0]]."(姓名：'".$json_msg['name']."',身份证号：'";
                if(isset($json_msg['identify_list'])&&isset($json_msg['identify_list'][0])){
                    $data['eventcontent'].=$json_msg['identify_list'][0]['card_no'];
                }
                $data['eventcontent'].="',出现在".$data['eventaddress'];
                if(isset($device)){
                    $data['eventlatitude']=$device['lat'];
                    $data['eventlongitude']=$device['lon'];
                    //$data['eventaddress'].='-'.$device['position'];
                    //$data['eventcontent'].=$device['position'];
                }else{
                    $data['eventlatitude']=0;
                    $data['eventlongitude']=0;
                }
                $data['eventjd']=substr($shid,0,9);
                $data['eventsq']=$shid;
                $data['eventsjrs']=1;
                $tjrxm='简阳广电';
                $tjrlxfs='15680982305';
                if(isset($shequ['name'])){
                    $tjrxm=$shequ['name'];
                }
                if(isset($shequ['phone'])){
                    $tjrlxfs=$shequ['phone'];
                }

                $data['tgrxm']=$tjrxm;
                $data['tgrlxfs']=$tjrlxfs;
                $data['tgrxb']='1';
                $data['createtime']=date('Y-m-d H:i:s');
                $data['informsource_value']=55;
                //$data['fileurl']=$json_msg['album_photo_url'].','.$json_msg['capture_face_url'];
                //$data['filenames']=$dldcode.'1,'.$dldcode.'2';
                $data['filenames']=$dldcode.'.jpg';
                //http://10.1.232.3:8080/tgdld   账号znyjdj   密码znyjdj1234
                //$posts['dto.fileds']=base64_encode(file_get_contents($json_msg['album_photo_url'])).','.base64_encode(file_get_contents($json_msg['capture_face_url']));
                $posts['dto.fileds']=base64_encode(file_get_contents($json_msg['capture_face_url']));
                echo $posts['dto.fileds'];
                //,'images'=>$posts['dto.fileds']
                //$res=$this->json_post($url,$data,[]);
                $res='{"code"=>1}';
                Db::table('send_msg')->where('id',$insert_id)->update(['send_msg'=>json_encode($data),'rec_msg'=>$res,'small_category'=>$notes[0]]);
                $res=json_decode($res,true);
                if(isset($res['resultCode'])&&$res['resultCode']==1){
                    Db::table('send_msg')->where('id',$insert_id)->update(['status'=>1,'eventid'=>$res['eventid']]);
                }else{
                    Db::table('send_msg')->where('id',$insert_id)->update(['status'=>0]);
                }
            }
        }catch (\Exception $e){
            Db::table('error_log')->insert(['msg'=>$msg->body,'error_log'=>$e->getTraceAsString(),'create_time'=>date('Y-m-d H:i:s')]);
        }
    }

    private function getAlbum(){
        $albums=[];
        $albums=Cache::get('album');
        if(!$albums){
            $album=file_get_contents("http://10.229.0.19:9100/api/public/album/listAlbums?caller_id=000002&version=v5&api_id=A001&access_token=f3d9a0f0d3bf4416ad9baf96168e9ef2&album_type=2");
            $o_album=json_decode($album,true);
            if(isset($o_album['data']['results'])){
                $o_albums=$o_album['data']['results'];
                foreach ($o_albums as $single) {
                    $albums[$single['album_id']]=$single['note'];
                }
            }else{
                $albums=[];
            }
            Cache::set('album',$albums,3600);
        }
        return $albums;
    }

    private function getCamare(){
        $camares=Cache::get('camare');
        if(!$camares){
            $camare=file_get_contents("http://10.229.0.19:9100/api/public/device/listDevices?caller_id=000002&version=v5&api_id=D001&access_token=f3d9a0f0d3bf4416ad9baf96168e9ef2&device_type=2");
            $o_camares=json_decode($camare,true);
            if(isset($o_camares['data']['results'])){
                $o_camares=$o_camares['data']['results'];
                foreach ($o_camares as $single) {
                    $camares[$single['device_id']]['lat']=$single['lat'];
                    $camares[$single['device_id']]['lon']=$single['lon'];
                    $camares[$single['device_id']]['position']=$single['position'];
                    $camares[$single['device_id']]['sqid']=$single['note'];
                }
            }else{
                $camares=[];
            }
            Cache::set('camare',$camares,3600);
        }
        return $camares;
    }

    private function getShequ(){
        $a='[{"shequId":"510185001011","shequName":"金水街社区","lianxirenPhone":"18784303257"},{"shequId":"510185001015","shequName":"政府街社区","lianxirenPhone":"18481185554"},{"shequId":"510185001001","shequName":"安象街社区","lianxirenPhone":"15182159216"}]';
        $a=json_decode($a,true);
        foreach ($a as $item) {
            $res['name']=$item['shequName'];
            $res['phone']=$item['lianxirenPhone'];
            $result[$item['shequId']]=$res;
        }
        return $result;
    }

    public function save_img(){
        $_face=new Faces();
        //$_face->saev_face($img);
    }

    public function create_album(){
        $url='http://220.166.79.246:30910/api/public/album/listAlbums?caller_id=000003&access_token=72518cc85a414578815f161acd16bb51&version=v5&api_id=A001';
        //$data=file_get_contents($url);
        $data=[
            'album_type'=>2,
            'name'=>'智慧小区1',
            ''
        ];
        $res=Http::post($url,json_encode($data),[CURLOPT_HTTPHEADER=>['Content-Type:application/json']]);
        var_dump($data);
        Http::post('',$data,[CURLOPT_HTTPHEADER=>['Content-Type:application/json']]);
    }

    public function getzipinfolist(){
        $gets=Request::get();
        $content=file_get_contents('https://ezc.chinapopin.com/zhxq-manager/feedback/zip/page?'.http_build_query($gets));
        $this->success('获取成功',json_decode($content));

    }

    public function test_sms($mobile){
        $sms=config('capture.sms');
        $client = new Client($sms['app_code']);
        $res=$client->smsSend()
            ->withSignId($sms['sign_id'])
            ->withTemplateId($sms['template_id'])
            ->withPhone($mobile)
            ->request();
        var_dump($res);
    }

    public function get_fe() {
        $_faceF=new FacesFeature();
        $lists=$_faceF->where('feature','<>','')->order('id desc')->limit(300000)->column('feature');
        $fp=fopen('/www/wwwroot/neijiang.abcve.com/public/1.txt','w');
        foreach($lists as $k=>$v){
            fwrite($fp,$v."\n");
        }
        fclose($fp);
    }

    public function test1($id=980){
        $feature=AlbumFeature::find($id);
        $_feature=new Feature();
        $res=$_feature->compare_all_feature($feature['feature'],'album',0.55,'2024-12-08 00:00:00','2025-01-10 00:00:00',1111);
        var_dump($res);
    }

    public function test2($id=980){
        $feature=AlbumFeature::find($id);
        $_feature=new Feature();
        $res=$_feature->compare_feature($feature['feature'],'album',55,1111);
        var_dump($res);
    }

    public function test3() {
        $tasks = Task::getAvaTask(51,87);
    }
    public function test4($sn=123) {
        $mqttServer = app(MqttServer::class);
        $msg=array(
            'client_id'=>111,
            'cmd_id'=>1111,
            'version'=>'0.2',
            'cmd'=>'create_face',
            'per_id'=>"1111",
            'per_name'=>'1111',
            'idcardNum'=>'0',
            'idcardper'=>'0',
            'img_url'=>'https://inews.gtimg.com/news_bt/OLfEe7AppXargZmhOREeZXeWMVLOveio8ywtgpg5ODLBYAA/641',
            'per_type'=>1,
            'usr_type'=>0,
            's_time'=>0,
            'e_time'=>100
        );
        $mqttServer->publish('face/'.$sn.'/request', json_encode($msg));
    }

    public function test5($id=1){
        $_feature=new AlbumFeature();
        $all_ids=$_feature->where('id','>',$id)->limit(100)->select();
        foreach ($all_ids as $feature){
            $id=$feature['id'];
            echo $id.":";
            //$feature=$feature->feature;
            $features=Db::name('album_feature')->where('id','>',$id)->chunk(2000,function ($features) use ($feature) {
                foreach($features as $k=>$v){
                    $_face=new Faces();
                    $_feature=new AlbumFeature();
                    $_photo=new AlbumPhoto();
                    if($v['id']!=$feature['id']){
                        $res=$_face->compare_feature_str($feature->feature,$v['feature']);
                        //echo $v['id'].":".$res."<br>";
                        if($res>50){
                            echo $v['id'].";";
                            //var_dump($v);
                            $_face->where('photo_id',$v['id'])->save(['photo_id'=>$feature['id'],'scores'=>$res]);
                            $_feature->where('id',$v['id'])->delete();
                            $_photo->where('id',$v['id'])->delete();
                            $_photo->where('id',$feature['id'])->inc('show_num')->update();
                        }

                    }
                }
            });
            echo "<br>";
        }




    }

    public function test6($id=1){
        $_feature=new AlbumFeature();
        $all_ids=$_feature->where('id',$id)->select();
        foreach ($all_ids as $feature){
            $id=$feature['id'];
            echo $id.":";
            //$feature=$feature->feature;
            $features=Db::name('album_feature')->where('id','>',$id)->chunk(2000,function ($features) use ($feature) {
                foreach($features as $k=>$v){
                    $_face=new Faces();
                    $_feature=new AlbumFeature();
                    $_photo=new AlbumPhoto();
                    if($v['id']!=$feature['id']){
                        $res=$_face->compare_feature_str($feature->feature,$v['feature']);
                        //echo $v['id'].":".$res."<br>";
                        if($res>50){
                            echo $v['id'].";";
                            //var_dump($v);
                            $_face->where('photo_id',$v['id'])->save(['photo_id'=>$feature['id'],'scores'=>$res]);
                            $_feature->where('id',$v['id'])->delete();
                            $_photo->where('id',$v['id'])->delete();
                            $_photo->where('id',$feature['id'])->inc('show_num')->update();
                        }

                    }
                }
            });
            echo "<br>";
        }




    }

    public function test7($id=1){
        $_album_feature=new AlbumFeature();
        $_face=new Faces();
        $_photo=new AlbumPhoto();
        $fp=fopen("test7.log",'a+');
        $all_ids=$_album_feature->where('id','>',$id)->limit(5000)->select();
        foreach ($all_ids as $feature){
            $id=$feature['id'];
            echo $id.":";

            $str='';
            $_feature=new Feature();
            $res=$_feature->compare_feature1($feature['feature'],'album',50,11111);
            foreach ($res as $re) {
                if($re['id']>$feature['id']){
                    echo $re['id'].";";
                    $str.=$re['id'].";";
                    //var_dump($v);
                    $_face->where('photo_id',$re['id'])->save(['photo_id'=>$feature['id'],'scores'=>$res]);
                    $_album_feature->where('id',$re['id'])->delete();
                    $_photo->where('id',$re['id'])->delete();
                    $_photo->where('id',$feature['id'])->inc('show_num')->update();
                }
            }
            Cache::set('cal_id',$id,36000000);
            //$feature=$feature->feature;
            //var_dump($res);
            echo "<br>";
            fwrite($fp,date('Y-m-d H:i:s').'   '.$id.":");
            fwrite($fp,$str);
            fwrite($fp,"\n");
        }
    }

    public function test8($id=1){
        $_album_feature=new AlbumFeature();
        $_face=new Faces();
        $_photo=new AlbumPhoto();
        $fp=fopen("test8.log",'a+');
        $all_ids=$_album_feature->where('id','>',$id)->limit(10000)->select();
        $delete=[];
        foreach ($all_ids as $feature){

            $id=$feature['id'];
            if(in_array($id,$delete)){
                fwrite($fp,date('Y-m-d H:i:s').'   '.$id."已删\n");
                continue;
            }
            echo $id.":";

            $str='';
            $_feature=new Feature();
            $res=$_feature->compare_feature2($feature['feature'],'album',50,'id_'.$feature['id']);
            foreach ($res as $re) {
                if($re['id']>$feature['id']){
                    $delete[]=$re['id'];
                    echo $re['id'].";";
                    $str.=$re['id'].";";
                    //var_dump($v);
                    $_face->where('photo_id',$re['id'])->save(['photo_id'=>$feature['id'],'scores'=>$res]);
                    $_album_feature->where('id',$re['id'])->delete();
                    $_photo->where('id',$re['id'])->delete();
                    $_photo->where('id',$feature['id'])->inc('show_num')->update();
                }
            }
            Cache::set('cal_id',$id,36000000);
            //$feature=$feature->feature;
            //var_dump($res);
            echo "<br>";
            fwrite($fp,date('Y-m-d H:i:s').'   '.$id.":");
            fwrite($fp,$str);
            fwrite($fp,"\n");
        }
    }

    public function test9($id=1){
        $_album_feature=new AlbumFeature();
        $_face=new Faces();
        $_photo=new AlbumPhoto();
        $all_ids=$_album_feature->where('id','>',$id)->limit(1)->select();
        $delete=[];
        foreach ($all_ids as $feature){

            $id=$feature['id'];
            if(in_array($id,$delete)){
                continue;
            }
            echo $id.":";

            $str='';
            $_feature=new Feature();
            $res=$_feature->compare_feature3($feature['feature'],'album',50,'id_'.$feature['id']);
            var_dump($res);
            //$feature=$feature->feature;
            //var_dump($res);
            echo "<br>";
        }
    }
}
